#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define NUM_ARGS (argc - 1)

#ifndef EXECVP
extern long get_number_of_bytes(const char *fpath);
#endif

void print_file_size(const char *fpath);

int main(int argc, char *argv[]){
    char **fpaths = argv + 1;
    pid_t *pids = malloc(sizeof(pid_t) * NUM_ARGS);
    memset(pids, 0, sizeof(pid_t) * NUM_ARGS);
    for(int i = 0; i < NUM_ARGS; ++i)
    {
        pids[i] = fork();
        switch(pids[i])
        {
            case 0:
#ifdef EXECVP
                char *const cmd[3] = { "./get_number_of_bytes", fpaths[i], NULL };
                execvp(cmd[0], cmd);
                perror("execvp");
#else
                print_file_size(fpaths[i]);
#endif
                break;
            case -1:
                perror("fork");
                break;
            default:
                break;
        }
    }

    for(int i = 0; i < NUM_ARGS; ++i)
        wait(&pids[i]);

    free(pids);

    return 0;
}

#ifndef EXECVP
void print_file_size(const char *fpath)
{
    long size = get_number_of_bytes(fpath);
    //The get_number_of_bytes function already prints an error by itself
    if(size != -1)
        printf("%s is %ld bytes long\n", fpath, size);
    _exit(0);
}
#endif
